package com.cuje.coolrtc.activity;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.cuje.coolrtc.App;
import com.cuje.coolrtc.R;
import com.cuje.coolrtc.base.BaseActivity;
import com.cuje.coolrtc.custom.GameView;
import com.p2p.core.P2PFacade;
import com.p2p.define.P2PRoomType;
import com.p2p.listener.P2PGlobalListener;
import com.p2p.listener.P2PRoomListener;
import com.p2p.model.P2PError;
import com.p2p.model.P2PRoom;
import com.p2p.model.P2PUser;

import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.MediaStream;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

public class GameActivity extends BaseActivity implements P2PGlobalListener {
    private final static String TAG = GameActivity.class.getCanonicalName();

    private Context mContext;
    private GameView myGameView;
    private Timer timer;
    private LinearLayout.LayoutParams myParams;
    private ConcurrentHashMap<String, GameView> gameViewMap = new ConcurrentHashMap<>();
    private FrameLayout rootView;
    private P2PRoom mRoom;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_game);
        mContext = this;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        rootView = findViewById(R.id.fl_root);
        timer = new Timer();
        myParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        P2PFacade.onCreate(this, App.getUid(), App.getUserName());
    }

    @Override
    public void onInitSuccess() {
        P2PFacade.joinRoom("2345", P2PRoomType.Text, new P2PRoomListener() {
            @Override
            public boolean checkPermission() {
                return false;
            }

            @Override
            public void onJoinSuccess(final P2PRoom room) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mRoom = room;
                        myGameView = new GameView(mContext, Build.BRAND, true);
                        rootView.addView(myGameView, myParams);
                        sendXY();
                    }
                });
            }

            @Override
            public void onStatusChanged(final P2PUser user, final String newStatus) {
                Log.e(TAG, user.getName() + "-onStatusChanged-" + newStatus);
            }

            @Override
            public void onLocalStream(MediaStream localStream) {

            }

            @Override
            public void onAddRemoteStream(P2PUser user) {

            }

            @Override
            public void onRemoveRemoteStream(P2PUser user) {

            }

            @Override
            public void onDataChannelTextMessage(final P2PUser p2PUser, final String message) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = new JSONObject(message);
                            String action = jsonObject.optString("action");
                            switch (action) {
                                case "move":
                                    GameView gameView = gameViewMap.get(p2PUser.getId());
                                    if (gameView != null) {
                                        gameView.setMyColor(jsonObject.optInt("color"));
                                        gameView.setXY(Float.parseFloat(jsonObject.optString("x")), Float.parseFloat(jsonObject.optString("y")));
                                    }
                                    break;
                                default:
                                    break;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public void onUserJoined(final P2PUser user) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        GameView gameView = new GameView(mContext, user.getName(), false);
                        rootView.addView(gameView, myParams);
                        gameViewMap.put(user.getId(), gameView);
                    }
                });
            }

            @Override
            public void onUserLeft(final P2PUser user) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        GameView gameView = gameViewMap.get(user.getId());
                        rootView.removeView(gameView);
                    }
                });
            }
        });
    }

    @Override
    public void onInitFailure(P2PError error) {

    }

    @Override
    public void onRoomCreateSuccess(P2PRoom room) {

    }

    @Override
    public void onRoomCreateFailure(P2PRoom room, P2PError error) {

    }

    @Override
    public void onLeaveRoomSuccess(P2PRoom room, P2PUser self) {

    }

    @Override
    public void onLeaveRoomFailure(P2PRoom room, P2PError error) {

    }

    @Override
    public void onGetUserListSuccess(P2PRoom room, List<P2PUser> userList) {

    }

    @Override
    public void onGetUserListFailure(P2PRoom room, P2PError error) {

    }

    @Override
    public void onGetRoomListSuccess(String groupId, List<P2PRoom> roomList) {

    }

    @Override
    public void onGetRoomListFailure(String groupId, P2PError error) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        timer.cancel();
        timer.purge();
        if (mRoom != null) {
            mRoom.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mRoom != null) {
            mRoom.onResume();
            sendXY();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
        timer.purge();
        if (mRoom != null) {
            mRoom.onDestroy();
        }
    }

    private void sendXY() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.putOpt("action", "move");
                    jsonObject.putOpt("x", myGameView.getX());
                    jsonObject.putOpt("y", myGameView.getY());
                    jsonObject.putOpt("color", myGameView.getMyColor());
                    if (mRoom != null) {
                        mRoom.dataChannelTalk(jsonObject.toString());
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
            }
        }, 0, 1000 / 30);
    }
}
